<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/***
* @author     Dennis T. Kaplan
* @copyright  Copyright (c) 2007, PzzAzz LLC
* @link       http://www.pzzazz.com
* @created    Aug 3, 2007
* @since      Aug 3, 2007
* @version    1.0
* @license    GPL
* @package    CodeIgniter
* @subpackage Road side billboards
* @filesource
***/

/*************************************************************************
*                                                                       *
* Copyright (c) 2007 PzzAzz LLC                                         *
* All rights reserved.                                                  *
*                                                                       *
* This script is free software; you can redistribute it and/or modify   *
* it under the terms of the GNU General Public License as published by  *
* the Free Software Foundation;                                         *
*                                                                       *
* The GNU General Public License can be found at                        *
* http://www.gnu.org/copyleft/gpl.html.                                 *
*                                                                       *
* This script is distributed in the hope that it will be useful,        *
* but WITHOUT ANY WARRANTY; without even the implied warranty of        *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the          *
* GNU General Public License for more details.                          *
*                                                                       *
************************************************************************/

class roadside extends Controller 
{
    function __construct()
    {
        parent::Controller();
        $this->load->model('Tamer_Model', 'tm');
        $this->load->helper('img');
        $this->setVars();
//        $this->load->library('profiler');
        log_message('debug', "Billboard->RoadSide: Controler Class Initialized");
    }
    
    private function setVars()
    {
        $this->tpl['title'] = "Road Side Billboards";
        $this->tpl['sidebar'] = $this->tm->randomBlock();
        $this->tpl['head'] = '';
        $this->tpl['body'] = '';
        $this->db_table = 'bb_roadside';
        $this->org_id = FALSE;
        $this->tpl['tpljs'][]  = '';
        $this->tpl['head'] = '';
        
        $this->space = '<img src="/img/icon/blank.png" alt="" width="10" />';
    }

    /**
     * @note	Browse
     * @info	Browse available Road Side Billboards
     * @author	Dennis T. Kaplan
     * @access	public
     * @param	 
     * @return	html string
     + @icons from /usr/share/icons/Tangerine/32x32
     */	
    public function index()
    {
        $this->tpl['body'] .= '<a href="/billboard/roadside/edit"><button>Click here to post your static outdoor billboard</button></a><hr />';
    	$result = $this->browse_DB();
        if($result !== FALSE){
            $this->load->library('table');
            foreach($result as $row){
                if($row['Postcode'] > 0){
                    $query = $this->db->query('SELECT `city`, `state` FROM `places_postcode` WHERE `id` = '.$row['Postcode'].' LIMIT 1');
                    if ($query->num_rows() > 0) {
                        $p = $query->row();
                        $row['City'] = $p->city.', '.$p->state ;
                        unset($row['Postcode']);
                    }
                }
                $row['Street'] = '<a href="/billboard/roadside/view/'.$row['id'].'"><button>'.$row['Street'].'</button></a>';
                unset($row['id']);
                $this->table->add_row($row);
            }
            $this->table->set_heading(array_keys($row));            
            $this->tpl['body'] .= $this->table->generate();
            $this->table->clear();
            $this->load->view('blank', $this->tpl);
        }else{
            redirect('dbview/pages/error_db', 'location');
        }
    }

    /**
     * @note	get_browse
     * @author	Dennis T. Kaplan
     * @access	private
     * @param	 
     * @return	object
     */	
    private function browse_DB()
    {
        $results = '';
    	$query = $this->db->query("SELECT `id`, `Street`, `Postcode` FROM $this->db_table LIMIT 10");
        if ($query->num_rows() > 0) {
            foreach($query->result_array() as $k => $v){
                $results->$k = $v;
            }
        } else {
            $results = FALSE;
        }
        return $results;
    }



    /**
     * @note	View
     * @info	View details
     * @author	Dennis T. Kaplan
     * @access	public
     * @param	 
     * @return	html
     */	
    public function view()
    {
        $this->load->library('table');
        $this->load->helper('img');
        $id = $this->uri->segment(4);
        $this->tpl['sidebar']  = '<h2 class="SideBar">Rate</h2><p class="SideBar">Dollar per Month</p><hr />';
        $this->tpl['sidebar'] .= '<h2 class="SideBar">DEC</h2><p class="SideBar">Advertising exposure to Out-of-Home advertising is called Daily Effective Circulation ( DEC ). DEC is computed by using factors which calibrate period of exposure, directional traffic and vehicle occupancy.</p>';
        $this->tpl['sidebar'] .= '<p class="SideBar">Non-illuminated displays are allowed 12 hours of exposure, while illuminated displays are allowed 18 or 24 hours depending upon whether the lights are turned off at midnight or daybreak.</p>';
        $this->tpl['sidebar'] .= '<p class="SideBar">All two-way traffic is converted to effective directional traffic and DEC further converts traffic counts to people exposure. The current load factor used for adult 18+ vehicle occupancy is 1.35.</p>';
        
        $results = '';
    	$query = $this->db->query("SELECT * FROM `$this->db_table` WHERE `id` = $id LIMIT 1");
        if ($query->num_rows() > 0) {
            $v = $query->row();
            $p = ''; // Postcode
            if($v->Postcode > 0){
                $query = $this->db->query('SELECT `city`, `state` FROM `places_postcode` WHERE `id` = '.$v->Postcode.' LIMIT 1');
                if ($query->num_rows() > 0) {
                    $p = $query->row();
                    $p = $p->city.', '.$p->state ;
                }
            }

            $this->tpl['body'] .= anchor('billboard/roadside/view/'.$id, '<button>Delete</button>');
            $this->tpl['body'] .= $this->space;
            $this->tpl['body'] .= anchor('billboard/roadside/edit/'.$id,'<button>Edit</button>').'<hr />';

            $row['Street'] = $v->Street;
            $row['City'] = $p;
            $row['Direction'] = $v->Direction;
 	 	 	
            $row['Width'] = $v->Width;
            $row['Height'] = $v->Height;
            $row['Illuminated'] = $v->Illuminated;
            $row['DEC'] = number_format($v->DEC);
            $row['Rate'] = '$'.number_format($v->Rate);
            $this->table->set_heading(array_keys($row));

            $this->tpl['body'] .= $this->table->generate($row);

            $this->tpl['body'] .= '<h2>Description</h2>'.$v->Info;
            $this->load->view('blank', $this->tpl);
        } else {
            redirect('dbview/pages/error_db', 'location');
        }
    }

    
    private function init_db()
    {
        if( (! isset($this->db_data)) && ($this->db_id != '') ) {

            $query = $this->db->query('SELECT * FROM '.$this->db_table.' WHERE id = '.$this->db_id.' LIMIT 1');
            
            if ($query->num_rows() > 0) {
                $this->db_data = $query->row_array();
            }
        }else{
                $fields = $this->db->list_fields($this->db_table);
                foreach ($fields as $field) $this->db_data[$field] = '';
        }
    }
    
    
    /**
     * @note	Edit
     * @info	
     * @author	Dennis T. Kaplan
     * @access	public
     * @param	 
     * @return	html
     */	
    public function edit()
    {
        //$this->auth->CheckTaMeR(2);
        $this->tpl['tpljs'][]  = 'jquery';
        $this->tpl['tpljs'][]  = 'jquery.bgiframe.min';
        $this->tpl['tpljs'][]  = 'jquery.dimensions';
        $this->tpl['tplcss'][]  = 'jquery.autocomplete';
        $this->tpl['tpljs'][]  = 'jquery.autocomplete';
        $this->tpl['tpljs'][]  = 'postcode';
        
        $this->load->library('pquery');
        $this->load->library('table');
        $this->load->helper('form');
        $this->load->helper('img');
        $this->db_id = $this->uri->segment(4);
        $this->tpl['sidebar']  = '<h2 class="SideBar">Rate</h2>';
        $this->tpl['sidebar'] .= '<p class="SideBar">Dollar per Month</p>';
        $this->tpl['sidebar'] .= '<p class="SideBar">(Please enter numbers only. We will do the formating.)</p>';
        $this->tpl['sidebar'] .= '<h2 class="SideBar">DEC</h2><p class="SideBar">Advertising exposure to Out-of-Home advertising is called Daily Effective Circulation ( DEC ). DEC is computed by using factors which calibrate period of exposure, directional traffic and vehicle occupancy.</p>';
        $this->tpl['sidebar'] .= '<p class="SideBar">Non-illuminated displays are allowed 12 hours of exposure, while illuminated displays are allowed 18 or 24 hours depending upon whether the lights are turned off at midnight or daybreak.</p>';
        $this->tpl['sidebar'] .= '<p class="SideBar">All two-way traffic is converted to effective directional traffic and DEC further converts traffic counts to people exposure. The current load factor used for adult 18+ vehicle occupancy is 1.35.</p>';
        $this->init_db();
        extract($this->db_data);

        $North = $East = $South = $West = FALSE;
        $Direction = explode(",", $Direction);
        foreach($Direction as $k=>$v){
            $$v = TRUE;
        }

        $class='';
        if(isset($this->validation->Street_error)){$class='FormErr'; }
        $form['Street'] = form_input(array(
                                      'name'     =>'Street',
                                      'id'       =>'Street',
                                      'value'    =>$Street,
                                      'size'     =>'30',
                                      'maxlength'=>'200',
                                      'class'=>$class
                                      )
                                 );
        
        $code = '';
        if($Postcode > 0){
            $query = $this->db->getwhere('places_postcode', array('id' => $Postcode), 1);
            if ($query->num_rows() > 0) {
                $v = $query->row();
            $code = "$v->code $v->city $v->state" ;
            $this->tpl['body'] .= '<script type="text/javascript">'.$this->pquery->hide('#Postcode').'</script>';
            }else{
                $code = 'Click here and select location with mouse';
            }
        }
        
        $class='';
        if(isset($this->validation->Postcode_error)){
            $class='FormErr'; 
        }
        $form['Postcode or City'] =  form_input(array(
                    'name'        => 'Postcode',
                    'id'          => 'Postcode',
                    'value'       => $Postcode,
                    'size'        => '10',
                    'class'       => $class,
                    'onclick'     => 'clearValue(this)'
                    )
                    ).'<span id="postresult"><a href="#" onclick= "editzip(this)">'.$code.'</a></span>';


        $form[2][''] = '<strong>Direction</strong>';
        $class='';
        if(isset($this->validation->Direction_error)){$class='FormErr'; }
        $form[2]['North'] = form_checkbox(array(
                                      'name'     =>'North',
                                      'id'       =>'North',
                                      'value'    =>'North',
                                      'title'    =>'North',
                                      'checked'  =>$North,
                                      'class'=>$class
                                      )
                                 );
        
        $class='';
        $form[2]['East'] = form_checkbox(array(
                                      'name'     =>'East',
                                      'id'       =>'East',
                                      'value'    =>'East',
                                      'title'    =>'East',
                                      'checked'  =>$East,
                                      'class'=>$class
                                      )
                                 );
        
        $form[2]['South'] = form_checkbox(array(
                                      'name'     =>'South',
                                      'id'       =>'South',
                                      'value'    =>'South',
                                      'title'    =>'South',
                                      'checked'  =>$South,
                                      'class'=>$class
                                      )
                                 );
        
        $form[2]['West'] = form_checkbox(array(
                                      'name'     =>'West',
                                      'id'       =>'West',
                                      'value'    =>'West',
                                      'title'    =>'West',
                                      'checked'  =>$West,
                                      'class'=>$class
                                      )
                                 );

        $form[3][''] = '<strong>Size In Feet</strong>';

        $class='';
        if(isset($this->validation->Width_error)){$class='FormErr'; }
        $form[3]['Width'] = form_input(array(
                                      'name'     =>'Width',
                                      'id'       =>'Width',
                                      'value'    =>$Width,
                                      'size'     =>'3',
                                      'maxlength'=>'10',
                                      'title'=>'Numeric (No signs)',
                                      'class'=>$class
                                      )
                                 );
        
        $class='';
        if(isset($this->validation->Height_error)){$class='FormErr'; }
        $form[3]['Height'] = form_input(array(
                                      'name'     =>'Height',
                                      'id'       =>'Height',
                                      'value'    =>$Height,
                                      'size'     =>'3',
                                      'maxlength'=>'10',
                                      'title'=>'Numeric (No signs)',
                                      'class'=>$class
                                      )
                                 );
        
        $tip = '<img src="/img/icon/tip.png" width="16" height="16" alt="Tip" title="Multi Check" />';
        $form[4][''] = '<strong>Illuminated</strong>';

        $class='';
        $onoff = FALSE;
        $form[4]['Yes'] = form_radio(array(
                                      'name'     =>'Illuminated',
                                      'id'       =>'IlluminatedYes',
                                      'value'    =>'Yes',
                                      'checked'  => $onoff,
                                      'class'=>$class
                                      )
                                 );
        $onoff = TRUE;
        $form[4]['No'] = form_radio(array(
                                      'name'     =>'Illuminated',
                                      'id'       =>'IlluminatedNo',
                                      'value'    =>'No',
                                      'checked'  => $onoff,
                                      'class'=>$class
                                      )
                                 );
        
        $class='';
        if(isset($this->validation->DEC_error)){$class='FormErr'; }
        $form[5]['DEC'] = form_input(array(
                                      'name'     =>'DEC',
                                      'id'       =>'DEC',
                                      'value'    =>$DEC,
                                      'size'     =>'7',
                                      'maxlength'=>'10',
                                      'title'=>'Numeric (No signs)',
                                      'class'=>$class
                                      )
                                 ).$this->space.$this->space;
        
        $class='';if(isset($this->validation->Rate_error)){$class='FormErr';}
        $form[5]['Rate'] = ' $'.form_input(array(
                                      'name'     =>'Rate',
                                      'id'       =>'Rate',
                                      'value'    =>$Rate,
                                      'size'     =>'7',
                                      'maxlength'=>'10',
                                      'title'=>'Numeric (No signs)',
                                      'class'=>$class
                                      )
                                 );
        $class='';
        if(isset($this->validation->Info_error)){
            $class='FormErr'; 
        }
        $form['Info'] = form_textarea(array(
        'name'        => 'Info',
        'id'          => 'Info',
        'value'       =>  $Info,
        'rows'        => '10',
        'cols'        => '50',
        'class'       => $class
        )
        );

        $viewlink = '';
        if ($this->db_id != ''){
        	$viewlink = anchor('billboard/roadside/view/'.$this->db_id,'<button>Back to View</button>');
        }
        
        $form[''] = form_submit(array('class' => 'submit', 
        'name'        => 'save',
        'value'       => 'Save',
        'style'       => 'margin:10px'
        )
        ).$viewlink;
        $this->load->library('table');
        define('URI',$this->uri->segment(1).'/'.$this->uri->segment(2));
        $this->tpl['body'] .= form_open(URI);
        $this->tpl['body'] .= $this->table->form_table($form, 'padding-top:20px;padding-left:50px;');
        $this->tpl['body'] .= '</form>';

        if($Postcode > 0){
            $this->tpl['body'] .= '<script type="text/javascript">'.$this->pquery->hide('#Postcode').'</script>';
        }
        $this->load->view('blank', $this->tpl);

    }

    
    /**
     * @note	Validate
     * @info	
     * @author	Dennis T. Kaplan
     * @access	public/private
     * @param	Vars array string mixed 
     * @return	
     */	
    private function valiadte()
    {
        $this->load->library('validation');
        $rules['Street']   = 'trim|required|min_length[5]|max_length[50]|xss_clean';
        $rules['Postcode'] = 'callback_postcode';
        $rules['North']		    = 'trim|max_length[1]';
        $rules['East']		    = 'trim|max_length[1]';
        $rules['South']		    = 'trim|max_length[1]';
        $rules['West']		    = 'trim|max_length[1]';
        $rules['Width']		    = 'trim|max_length[3]';
        $rules['Height']	    = 'trim|max_length[3]';
        $rules['Illuminated']	= 'trim|required|max_length[3]';
        $rules['DEC']	        = 'trim|numeric|max_length[10]';
        $rules['Rate']	        = 'trim|numeric|min_length[2]|max_length[10]';
        $rules['Info']  		= "trim|min_length[10]|max_length[500]|xss_clean";

        $this->validation->set_rules($rules);
        $valResult = $this->validation->run();    	
        delids($this->db_data);
        $this->post = array();
        $count = 0;
        foreach($this->db_data as $k => $v){
            if(isset($this->validation->$k)){
                $p = $this->validation->$k;

                if($p != $v){
                    $count++;
                    if($k == 'Phone' || $k == 'FAX'){
                        $this->post[$k] = format_phone($p);
                    }else{
                        $this->post[$k] = $p;
                    }
                }
            }else{
                if(!isset($this->post[$k]) && $v != ''){
                    $count++;
                    $this->post[$k] = '';
                }
            }
        }
        $this->db_data = array_merge($this->db_data, $this->post);
        if($count == 0)
        {
            $this->msg->setError('Not Updated');
            $this->msg->setMsg('You have not made any changes.');
            return FALSE;
        }elseif($valResult != 1){
            return FALSE;
        }elseif($count > 0){
            return TRUE;
        }
    }
    
    /* Postcode validation callback function  */
    private function postcode($str)
	{
		if ($str < 10000000 || $str > 20000000)
		{
            $this->validation->set_message('postcode_check', 'You must select the %s with the mouse from the list');
			return FALSE;
		}
		else
		{
            $this->validation->Postcode = $str;
			return TRUE;
		}
	}

    /**
    * @note	index
    * @info	Just forwarding
    * @author	Dennis T. Kaplan
    * @access	public
    * @param	 
    * @return	html page
    */	
    public function post()
    {
        $this->initdb();
        if($this->input->post('save') !== FALSE)
        {
            if($this->validate() === TRUE)
            {
                $this->save();
            }
        }
        $this->index();
    }
    public function delete()
    {
        $this->auth->CheckTaMeR(2);
        $this->uid = $this->tm->get_uid();
        $db_id = $this->uri->segment(4);
        $oid = $this->tm->get_Org_id();
        $this->db->select('id');
        $this->db->where('org_id', $oid);
        if($this->uid != 1){
            $this->db->where('id', $db_id);
        }
        $query = $this->db->get($this->db_table);
        if ($query->num_rows() > 0)
        {
            $row = $query->row();
            $this->db->delete($this->db_table, array('id' => $db_id));
            redirect('billboard/roadside', 'location');
        }else{
            $this->msg->setError('No record found');
            $this->msg->setMsg("You might not have delete access to that item");
            $this->msg->setMsg('Please contact web support');
        }
    }

    private function save()
    {
        if($this->db_id !== FALSE)
        {
            log_message('info', 'update id: '. $this->db_id);
            $this->db->where('id', $this->db_id);
            $this->db->update($this->db_table, $this->post);
            $this->msg->setMsg('Your record has been updated');
        }else{
            $this->db->insert($this->db_table, $this->post);
            $this->db_id = $this->db->insert_id();
            $sql = "INSERT INTO `contact_user_org` (`id`, `user_id`, `org_id`) VALUES (NULL, '$this->uid', '$this->db_id');";
            $this->db->query($sql);
            log_message('info', 'insert id: '. $this->db_id);
            $this->msg->setMsg('Your record has been added');
        }
    }
}
?>
